package com.bowlong.third.payment.pp;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import com.bowlong.lang.NumEx;
import com.bowlong.net.http.HttpParser;
import com.bowlong.util.MapEx;
import com.bowlong.util.Ref;

public class Payment25PP {
	public static final String FAIL = "fail";
	public static final String SUCC = "success";

	public static boolean checkOrder(byte[] body, Ref<Double> money,
			Ref<Integer> orderId, Ref<String> errMsg, Ref<String> retToChannel) throws IOException {
		if (body == null || body.length <= 0) {
			money.val = 0.0;
			orderId.val = 0;
			retToChannel.val = FAIL;
			errMsg.val = "body == null || body.isEmpty()";
			return false;
		}
		// 处理充值回调
		String enc = new String(body, "UTF-8");
		int p1 = enc.indexOf("order_id=");
		int p2 = enc.indexOf("&sign=");
		if (p1 < 0 || p2 <= 0) {
			money.val = 0.0;
			orderId.val = 0;
			retToChannel.val = FAIL;
			errMsg.val = "body not found order_id and sign";
			return false;
		}

		String str = enc.substring(p1, p2);
		// String sign = enc.substring(p2 + 6, enc.length());

		Map<String, List<String>> map = HttpParser.parseQueryString(str,
				"UTF-8");
		if (map == null || map.isEmpty()) {
			money.val = 0.0;
			orderId.val = 0;
			retToChannel.val = FAIL;
			errMsg.val = "body parse error";
			return false;
		}
		// {"account":"888","amount":"0.01","order_id":"2012071076302411","billno":"2012071076302411","status":"1"}
		// String account = (String) MapEx.getList(map, "account").get(0);
		double amount = NumEx.stringToDouble((String) MapEx.getList(map,
				"amount").get(0));
		// String order_id = (String) MapEx.getList(map, "order_id").get(0);
		int billno = NumEx.stringToInt((String) MapEx.getList(map, "billno")
				.get(0));
		int status = NumEx.stringToInt((String) MapEx.getList(map, "status")
				.get(0));

		{ // 数据校验
			// Map encrypt = RSAEncrypt.decode(sign);
			// String eoid = MapEx.getString(encrypt, "order_id");
			// int ebillno = MapEx.getInt(encrypt, "billno");
			// if (!eoid.equals(order_id) || billno != ebillno) {
			// // 数据校验错误
			// res.setContent(ChannelBuffers.copiedBuffer("fail",
			// CharsetUtil.UTF_8));
			// setHeaders(res);
			// ChannelFuture future = me.getChannel().write(res);
			// future.addListener(ChannelFutureListener.CLOSE);
			// // dealyDlose(me.getChannel());
			// return;
			// }
		}

		if (status == 0 || status == 1) { // 状态: 0正常状态 1已兑换过并成功返回
			money.val = amount;
			orderId.val = billno;
			retToChannel.val = SUCC;
			errMsg.val = "status: " + status + " is ok";
			return true;
		} else{
			money.val = 0.0;
			orderId.val = 0;
			retToChannel.val = SUCC;
			errMsg.val = "status: " + status + " error";
			return false;
		}
	}
}
